package com.tk.service;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tk.component.SerialPortManager;
import com.tk.constant.ProductionLineProperties;
import com.tk.eneity.PdfObj;
import com.tk.utils.HttpUtils;
import com.tk.utils.ObjUtils;
import com.tk.utils.PdfUtil;
import com.tk.utils.SysConfigUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;


@Slf4j
@Service
public class SerialPortService {
    public static final String PREFIX = "ProductionLine-";

    @Autowired
    private ProductionLineProperties productionLineProperties;
    public static final String FILE_PATH = "src/main/resources/config.properties"; // 指向resources目录下的config.properties文件


    /**
     * 接受数据的回调方法
     */
    public void handlerData() {
        try {
            // 当前监听器监听到的串口返回数据 back
            byte[] back = SerialPortManager.readSerialPortData();
            processData(back);
        } catch (Exception e) {
            log.error("ERROR SerialPortCallback.dataAvailable cause:", e);
        }
    }


    private void processData(byte[] back) {

        if (ObjUtils.isEmpty(back)) return;

        String data = new String(back);

        // 判断数据是否包含 ProductionLine-
        if (data.startsWith(PREFIX)) {
            // 本地生成文件
            createConfigProperties(data.substring(PREFIX.length()));
            return;
        }

        // 调用接口发送数据
        String resultJson = null;
        String productionLine = productionLineProperties.getProductionLine();
        try {
            String param = "productionLine=" + productionLine + "&data=" + data;
            resultJson = HttpUtils.sendPost(SysConfigUtils.getConfigValue("scanner.send-address"), param);
            // 如果 resultJson 不为空, 打印PDF
            if (ObjUtils.isEmpty(resultJson)) return;
            ObjectMapper objectMapper = new ObjectMapper();
            PdfObj pdfObj = objectMapper.readValue(resultJson, PdfObj.class);
            PdfUtil.generatePdf(pdfObj);

        } catch (Exception e) {
            log.error("ERROR SerialPortCallback.processData cause:", e);
        } finally {
            log.info("PRO SerialPortCallback.processData productionLine:{},data:{}, resultJson:{}", productionLine, data, resultJson);
        }
    }


    public void createConfigProperties(String productionLine) {
        List<String> lines = List.of("productionLine=" + productionLine);

        try {
            Files.write(Paths.get(FILE_PATH), lines);
            log.info("PRO SerialPortCallback.createConfigProperties Config file created successfully! productionLine:{}", productionLine);
            productionLineProperties.setProductionLine(productionLine);
        } catch (IOException e) {
            log.error("ERROR SerialPortCallback.createConfigProperties cause:", e);
        }
    }

}

